#!/usr/bin/env python
# @Author  : Bright Li (brt2@qq.com)
# @Link    : https://gitee.com/brt2
# @Date    : 2022-12-01
# @Version : 0.2.2

import os.path
from pathlib import Path, PurePath
from typing import Callable, Dict, List, Union
from multiprocessing import Pool, cpu_count
import tqdm

def walk_dir(image_dir: Union[PurePath, str], recursive: bool=True) -> List:
    """ copy from: imagededup/utils/general_utils.py """
    glob_pattern = '**/*' if recursive else '*'
    return [
        i # i.absolute()
        for i in Path(image_dir).glob(glob_pattern)
        if not (i.name.startswith('.') or i.is_dir())
    ]

def parallelise(function: Callable, data: List, verbose: bool) -> List:
    """ copy from: imagededup/utils/general_utils.py
        使用python进程池，实现cpu并发
    """
    pool = Pool(processes=cpu_count())
    results = list(
        tqdm.tqdm(pool.imap(function, data, 100), total=len(data), disable=not verbose)
    )
    pool.close()
    pool.join()
    return results

# def rpath_curr(path_from_curdir, __file__):
#     curdir_ = os.path.dirname(__file__) if os.path.isfile(__file__) else __file__
#     return os.path.abspath(os.path.join(curdir_, path_from_curdir))

class RebasePath:
    """ 类似构建了一个目录的软连接 """
    def __init__(self, link_to=None, curfile=None, target_dir=None):
        """
        Usage:
            1. rpath = RebasePath(link_to='../xxx/yyy/')
               or:
               rpath = RebasePath(curfile=__file__, target_dir='/home/xxx/yyy/')
            2. rpath('ttt/xxx')
        """
        if link_to is None:
            curdir_ = curfile if os.path.isdir(curfile) else os.path.dirname(curfile)
            self.relative = os.path.relpath(target_dir, curdir_)
        else:
            self.relative = link_to

    def __call__(self, rpath_to_target_dir):
        """ return a ture-path of input """
        abspath_target = os.path.join(self.relative, rpath_to_target_dir)
        # logger.debug(f">>> {abspath_target}")
        return abspath_target

#####################################################################
# utils.expy@Version: 2.1.4
#####################################################################
import sys
import os

def path_expand(dir_lib, __file__=None, addsitedir=False):
    """ 当__file__为None时，dir_lib为绝对路径（或相对工作目录）
        否则，相对于传入的__file__所在目录引用dir_lib
    """
    if __file__ is not None:
        dir_lib = os.path.join(os.path.dirname(__file__), dir_lib)
    dir_lib_abs = os.path.abspath(dir_lib)
    if os.path.exists(dir_lib_abs):
        if dir_lib_abs not in sys.path:
            if addsitedir:
                import site
                str_func = "site_expand: "
                site.addsitedir(dir_lib_abs)
            else:
                str_func = "path_expand: "
                sys.path.append(dir_lib_abs)
            print(str_func + f"动态加载Lib目录【{dir_lib_abs}】")
    else:
        raise Exception(f"无效的路径【{dir_lib_abs}】")
        # print(f"path_append: 无效的路径【{dir_lib_abs}】")

def site_expand(dir_lib, __file__=None):
    """ 功能上强于path_append，会调用path目录下的*.pth文件
        但pyinstaller打包时，会提示site无法导入addsitedir问题
    """
    path_expand(dir_lib, __file__, True)

### venv manager ###
from platform import system

_VENV_PATH_SITE_PACKAGES = "lib/site-packages" if system() == "Windows" else \
    "lib/python{}.{}/site-packages".format(*sys.version_info[:2])

def venv_expand(path_venv):
    dir_lib = os.path.join(path_venv, _VENV_PATH_SITE_PACKAGES)
    # if not os.path.exists(dir_lib):
    #     raise Exception(f"无效的路径【{dir_lib}】")
    site_expand(dir_lib)

def topdir(dir_dst, override=False):
    dir_dst_abs = os.path.abspath(dir_dst)
    # 修改顶层目录
    if override:
        sys.path[0] = dir_dst_abs  # os.getcwd()
    else:
        sys.path.insert(0, dir_dst_abs)
    return dir_dst_abs

def enpy(folder_name):
    """ 注意，目前的配置目录仅自用（个人配置的所有venv目录均位于 '$HOME/.enpy' ）"""
    if folder_name[0] == '/':
        path_venv = folder_name
    elif folder_name[0] == '~':
        path_venv = os.path.expanduser(folder_name)
    else:
        if folder_name[0] == ".":  # 相对路径
            ENPY_PREFIX = os.path.abspath(os.path.curdir)
        else:
            ENPY_PREFIX = os.path.join(os.getenv("HOME"), ".enpy")
        path_venv = os.path.join(ENPY_PREFIX, folder_name)
    venv_expand(path_venv)

def expy_pydev():
    path_pydev = os.path.join(os.getenv("HOME"), "local/utils/pydev")
    site_expand(path_pydev)

#####################################################################
# end of expy
#####################################################################
